<?php

namespace app\common\service;

use app\common\model\Service;
use app\common\model\ServiceTag;
use app\common\model\StaffTag;
use app\common\model\Tag;
use app\http\exception\AuthException;

use think\facade\Db;

use function error_abort;

class TagService extends BaseService
{
    public function getTagPage($data)
    {
        $sql1 = Db::name('admin_tag')
                  ->field('tag_id ,count(*) admin_num')
                  ->group('tag_id')
                  ->buildSql();
        $sql2 = Db::name('service_tag')
                  ->field('tag_id ,count(*) service_num')
                  ->group('tag_id')
                  ->buildSql();
        return Tag::build()
                  ->alias('tt')
                  ->field('tt.* ,t1.admin_num , t2.service_num')
                  ->leftJoin([$sql1 => 't1'], 't1.tag_id = tt.tag_id')
                  ->leftJoin([$sql2 => 't2'], 't2.tag_id = tt.tag_id')
                  ->orderBy('tt.tag_id', 'desc')
                  ->_paginate()
                  ->each(function (Tag $item)
                  {
                      $item->admin_num = $item->admin_num ?? 0;
                      $item->service_num = $item->service_num ?? 0;
                  });
    }

    public function getTagList($data)
    {
        return Tag::build()
                  ->orderBy('tag_id', 'desc')
                  ->select();
    }

    public function getTagItem($id)
    {
        return Tag::build()
                  ->findOrFail($id);
    }

    public function delTagItem($ids)
    {
        StaffTag::build()
                ->where('tag_id', $ids)
                ->count() && error_abort('当前标签存在已使用的技师!');
        ServiceTag::build()
                  ->where('tag_id', $ids)
                  ->count() && error_abort('当前标签存在已使用的技师!');
        return Tag::build()
                  ->whereIn('tag_id', $ids)
                  ->delete();
    }

    public function setTagItem($data, $id)
    {
        $info = Tag::build()
                   ->findOrFail($id);
        if (!$info) {
            throw new AuthException('数据不存在');
        }

        $info->save($data);
        return $info;
    }


    public function addTagItem($data)
    {
        $model = new Tag();
        return $model->save($data);
    }


}
